package net.livingflow.web.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import net.livingflow.Constants;
import net.livingflow.model.Flow;
import net.livingflow.model.Pack;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.view.Viewable;

/**
 * @author xueqiang.mi
 * @since 2010-12-18
 */
@Path("/user")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class UserResource extends BaseResource {

	private long packId = 0;
	private String user;

	@GET
	@Path("{user}/{packId}")
	public Response byPack(@PathParam("user") String user, @PathParam("packId") long packId) {
		this.user = user;
		this.packId = packId;
		return Response.ok(new Viewable("index", this)).build();
	}

	public List<Flow> getFlows() {
		if (packId != 0) {
			return flowService.getByPack(packId);
		}
		return flowService.getLattestByUser(user, Constants.PAGE_SIZE);
	}

	public List<Pack> getPacks() {
		return packService.getByUser(user);
	}

	public String getUser() {
		return user;
	}

	@GET
	@Path("{user}")
	public Response getUser(@PathParam("user") String user) {
		this.user = user;
		return Response.ok(new Viewable("index", this)).build();
	}

	@POST
	@Path("ajax/mkFrid/With/{friend}")
	@Produces("text/plain")
	public String mkFriend(@PathParam("friend") String friend) {
		String user = getUserName();
		if (user == null) {
			return Constants.STATUS_ERROR + " 必须登录才能添加好友!";
		}
		if (user.equals(friend)) {
			return Constants.STATUS_ERROR + " 不能将自己添加为好友!";
		}
		accountService.addFriend(user, friend);
		return Constants.STATUS_DONE;
	}

	@POST
	@Path("ajax/register")
	@Consumes("application/x-www-form-urlencoded")
	@Produces("text/plain")
	public String postRegisterForm() {
		return Constants.STATUS_DONE;
	}
}
